package com.jason.lucene.example.index;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopFieldDocs;
import org.junit.Test;

/**
 * @author he peng
 * @create 2017/11/30 16:30
 * @see
 */
public class DocumentUpdateTest extends BaseIndexingTest {

    @Test
    public void update() throws Exception {
        // lucene 最初没有提供更新的 api , 通过先删除再写入的方式完成更新
        // 现在可以通过 IndexWriter.updateDocument() 来更新文档

        IndexWriterConfig conf = new IndexWriterConfig(getAnalyzer());
        conf.setUseCompoundFile(true);
        IndexWriter indexWriter = new IndexWriter(super.indexDir, conf);
        Term term = new Term("city", "Amsterdam");
        indexWriter.deleteDocuments(term);
        indexWriter.forceMergeDeletes();
        indexWriter.commit();

        FieldType unIndexFieldType = new FieldType();
        unIndexFieldType.setIndexOptions(IndexOptions.NONE);
        unIndexFieldType.setStored(true);

        Document document = new Document();
        document.add(new Field("id" , "1" , TextField.TYPE_STORED));
        document.add(new Field("country" , "Netherlands" , unIndexFieldType));
        document.add(new Field("contents" , "Amsterdam has lots if bridges" , TextField.TYPE_NOT_STORED));
        document.add(new Field("city" , "Haag" , TextField.TYPE_STORED));
        indexWriter.addDocument(document);
        System.out.println("add document : " + document);
        indexWriter.close();

        IndexReader indexReader = DirectoryReader.open(super.indexDir);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        QueryParser queryParser = new QueryParser("city" , getAnalyzer());
        Query query = queryParser.parse("Haag");
        TopFieldDocs topFieldDocs = indexSearcher.search(query, 1000, Sort.INDEXORDER);
        for (ScoreDoc scoreDoc : topFieldDocs.scoreDocs) {
            Document doc = indexSearcher.doc(scoreDoc.doc);
            System.out.println("score = " + scoreDoc.score + " , doc = " +
                    scoreDoc.doc + " , search result : " + doc);
        }

    }
}